#include "AppMsg.h"

#include <QLocalSocket>
#include <QCoreApplication>

AppMsg::AppMsg(const QString& name, QObject* parent)
    : QObject(parent), m_serverId(name)
{
    connect(&m_server, &QLocalServer::newConnection, this, &AppMsg::onNewConnection);
}

AppMsg::~AppMsg()
{
}

AppMsg &AppMsg::get()
{
    static AppMsg instance("ccoa-tool");
    return instance;
}

void AppMsg::sendMsg(const QString &msg)
{
    if (!m_socket) {
        return;
    }
    m_socket->write(msg.toUtf8());
}

QString AppMsg::getLastErrorString() const
{
    return m_server.errorString();
}

bool AppMsg::start()
{
    QLocalSocket *socket = new QLocalSocket;
    socket->connectToServer(m_serverId);
    bool flag = socket->waitForConnected();
    if (flag == true) {
        qDebug() << "client";
        m_socket = socket;
        connect(m_socket,&QLocalSocket::readyRead,this,&AppMsg::onProcess);
        connect(m_socket,&QLocalSocket::disconnected,this,[](){
            qApp->exit();
        });
    } else {
        delete socket;
        m_server.removeServer(m_serverId);
        flag = m_server.listen(m_serverId);
        qDebug() << "server";
    }
    return flag;
}

void AppMsg::onNewConnection()
{
    qDebug() << "connected";
    if (m_socket) {
        qDebug() << "error repetition";
        return;
    }

    m_socket = m_server.nextPendingConnection();
    connect(m_socket,&QLocalSocket::readyRead,this,&AppMsg::onProcess);
}

void AppMsg::onProcess()
{
    const QByteArray &msg = m_socket->readAll();
    emit hasMsg(msg);
}
